package com.mybatis.boost.tool;

import java.util.Optional;
import java.util.function.Consumer;

/**
 * 包装Optional对象，封装一些增强特性
 *
 * @author Jearton
 * @since 16/9/28
 */
@SuppressWarnings("all")
public class OptionalExt<T> {

    private final Optional<T> optional;

    private OptionalExt(Optional<T> optional) {
        this.optional = optional;
    }

    public static <T> OptionalExt<T> of(Optional<T> optional) {
        return new OptionalExt<>(optional);
    }

    /**
     * ifPresent可以和orElse连着用，符合函数式写法
     */
    public OptionalExt ifPresent(Consumer<T> consumer) {
        optional.ifPresent(consumer);
        return this;
    }

    public void orElse(Runnable runnable) {
        if (!optional.isPresent()) {
            runnable.run();
        }
    }
}
